﻿using Kylin.Wiki.IService;
using Kylin.Wiki.Model.Api;
using Kylin.Wiki.Model.Dto;
using Kylin.Wiki.Model.Entity;
using Kylin.Wiki.Model.View;
using Kylin.Wiki.Web.Common;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;

namespace Kylin.Wiki.Web.Controllers.Document
{
    [Route("api/[controller]")]
    [ApiController]
    public class DocumentUserController : BaseController
    {

        private readonly IDocument_UserService _documentUserService;

        public DocumentUserController(IDocument_UserService document_UserService)
        {
            _documentUserService = document_UserService;
        }

        [HttpGet]
        public ApiResult<List<DocumentUserVM>> Get(int wikiId)
        {
            return _documentUserService.GetDocumentUserList(wikiId);
        }

        [HttpPost]
        public ApiResult<bool> Create([FromBody] DocumentUserCreateDTO documentUserCreateDTO)
        {
            ApiResult<bool> result = new ApiResult<bool>();
            documentUserCreateDTO.CreateBy = UserContext.Current.UserName;
            documentUserCreateDTO.CreateOn = DateTime.Now;
            documentUserCreateDTO.UpdateBy = UserContext.Current.UserName;
            documentUserCreateDTO.UpdateOn = DateTime.Now;
            var documentUser = documentUserCreateDTO.Adapt<Document_User>();
            result.Data = _documentUserService.Add(documentUser, true) > 0;
            return result;

        }

        [HttpPut]
        public ApiResult<bool> Update([FromBody] DocumentUserUpdateDTO documentUserUpdateDTO)
        {
            ApiResult<bool> result = new ApiResult<bool>();
            var documentUser = _documentUserService.FindFirst(x => x.ID == documentUserUpdateDTO.ID);
            if (documentUser == null)
                return new ApiResult<bool>(false, Core.Enum.HttpStateCode.Error, "数据不存在");

            documentUser.UpdateBy = UserContext.Current.UserName;
            documentUser.UpdateOn = DateTime.Now;
            documentUser.Permission = documentUserUpdateDTO.Permission;

            result.Data = _documentUserService.Update(documentUser, true) > 0;
            result.Success = true;

            return result;
        }

        [HttpDelete("{id}")]
        public ApiResult<bool> Delete(int id)
        {
            ApiResult<bool> result = new ApiResult<bool>();
            var documentUser = _documentUserService.FindFirst(x => x.ID == id);
            if (documentUser == null)
                return new ApiResult<bool>(false, Core.Enum.HttpStateCode.Error, "数据不存在");
            var flag = _documentUserService.Delete(documentUser, true);
            result.Data = flag > 0;
            return result;
        }
    }
}
